<template>
  <el-select v-model="_value" multiple :multiple-limit="multipleLimit" filterable default-first-option :placeholder="placeholder" style="width: 100%;">
    <el-option v-for="item in tags" :key="item.id" :label="item.label" :value="item.id"></el-option>
  </el-select>
</template>

<script>
/**
 * hpro-select-tags
 * @desc 用户标签选择控件
 *
 * @param { array } value = 已选择的标签列表，用:value.sync绑定，格式[{id: 'id', label: 'label'}]
 * @param { number } multipleLimit = 最多可选几个标签，默认值为5
 * @param { string } placeholder = 提示文案，默认为“请选择标签，最多可选 5 个”
 */
export default {
  name: 'hpro-select-tags',
  componentName: 'hpro-select-tags',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: Array,
    multipleLimit: {
      type: Number,
      default: 5
    },
    placeholder: {
      type: String,
      default: '请选择标签，最多可选 5 个'
    }
  },
  data () {
    return {
      tags: []
    }
  },
  created () {
    this.getAllTags()
  },
  computed: {
    _value: {
      get () {
        let value = this.value
        let tmp = []
        value.map(element => {
          tmp.push(element.id)
        })
        return tmp
      },
      set (val) {
        let tags = this.tags
        let tmp = []
        val.map(element => {
          tags.map(item => {
            if (element === item.id) {
              tmp.push(item)
            }
          })
        })
        this.$emit('change', tmp)
        this.$emit('update:value', tmp)
      }
    }
  },
  methods: {
    // 获取会员标签列表
    getAllTags () {
      let tags = []
      let tmp = [
        {
          id: '1',
          label: '标签名称1'
        },
        {
          id: '2',
          label: '标签名称2'
        },
        {
          id: '3',
          label: '标签名称3'
        },
        {
          id: '4',
          label: '标签名称4'
        },
        {
          id: '5',
          label: '标签名称5'
        },
        {
          id: '6',
          label: '标签名称6'
        },
        {
          id: '7',
          label: '标签名称7'
        }
      ]
      tmp.map(element => {
        tags.push(element)
      })
      this.tags = tags
    }
  }
}
</script>
